package top.went.utils;


import top.went.exception.InputException;

import java.util.regex.Pattern;

/**
 * 正则验证
 */
public final class RegularUtils {
    /**
     * 账号用户名2-5个汉字
     */
    private static final Pattern ACCOUNT_NAME = Pattern.compile("^[\\u4e00-\\u9fa5]{2,5}$");
    /**
     * 账号密码 6-16位数字和字母的组合
     */
    private static final Pattern ACCOUNT_PASSWORD = Pattern.compile("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$");
    /**
     * 身份证 18位
     */
    private static final Pattern IDCODE = Pattern.compile("^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$");

    /**
     * 手机号码
     */
    private static final Pattern PHONE = Pattern.compile("^1[3|4|5|8][0-9]\\d{8}$");

    /**
     * 邮箱地址
     */
    private static final Pattern EMAIL = Pattern.compile("^([A-Za-z0-9_\\-\\.\\u4e00-\\u9fa5])+\\@([A-Za-z0-9_\\-\\.])+\\.([A-Za-z]{2,8})$");

    /**
     * 验证账号用户名
     *
     * @param str
     * @return
     * @throws InputException
     */
    public static boolean matchAccountName(String str) throws InputException {
        if (ACCOUNT_NAME.matcher(str).matches()) {
            return true;
        }
        throw new InputException("用户名格式不正确");
    }

    /**
     * 验证账号密码
     *
     * @param str
     * @return
     * @throws InputException
     */
    public static boolean matchAccountPassword(String str) throws InputException {
        if (ACCOUNT_PASSWORD.matcher(str).matches())
            return true;
        throw new InputException("密码格式不正确");
    }

    /**
     * 验证身份证
     *
     * @param str
     * @return
     * @throws InputException
     */
    public static boolean matchIDCODE(String str) throws InputException {
        if (IDCODE.matcher(str).matches()){
            return true;
        }
        throw new InputException("身份证号码格式不正确");
    }

    /**
     * 验证日期格式
     * @param str
     * @return
     */
    public static boolean matchDate(String str) throws InputException {
        if (str.matches("\\d{4}-\\d{1,2}-\\d{1,2}")) {
            return true;
        }
        throw new InputException("日期格式错误:" + str);
    }

    /**
     * 验证手机号码格式
     * @param str
     * @return
     * @throws InputException
     */
    public static boolean matchPhone(String str) throws InputException {
        if (PHONE.matcher(str).matches()){
            return true;
        }
        throw new InputException("手机号码格式不正确");
    }

    /**
     * 验证邮箱地址格式
     * @param str
     * @return
     * @throws InputException
     */
    public static boolean matchEmail(String str) throws InputException {
        if (EMAIL.matcher(str).matches()){
            return true;
        }
        throw new InputException("邮箱地址格式不正确");
    }
}
